<template>
  <div class="p-4 mx-auto max-w-xl">
    <h2 class="mb-4 text-xl font-bold">颜色转换工具</h2>
    <input v-model="hex" class="p-2 mb-2 w-full rounded border" placeholder="输入 HEX 颜色，如 #ff0000" />
    <div class="mb-2">RGB: <span>{{ rgb }}</span></div>
    <div class="mb-2">HSL: <span>{{ hsl }}</span></div>
    <div class="w-12 h-12 rounded border" :style="{background: hex}" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
const hex = ref('#ff0000')

function hexToRgb(hex) {
  let c = hex.replace('#', '')
  if (c.length === 3) c = c.split('').map(x => x + x).join('')
  if (c.length !== 6) return ''
  const n = c.match(/.{2}/g).map(x => parseInt(x, 16))
  return `rgb(${n[0]}, ${n[1]}, ${n[2]})`
}
function hexToHsl(hex) {
  let c = hex.replace('#', '')
  if (c.length === 3) c = c.split('').map(x => x + x).join('')
  if (c.length !== 6) return ''
  let r = parseInt(c.slice(0,2),16)/255, g = parseInt(c.slice(2,4),16)/255, b = parseInt(c.slice(4,6),16)/255
  let max = Math.max(r,g,b), min = Math.min(r,g,b)
  let h, s, l = (max+min)/2
  if(max==min){h=s=0}else{
    let d = max-min
    s = l>0.5 ? d/(2-max-min) : d/(max+min)
    switch(max){
      case r: h=(g-b)/d+(g<b?6:0); break
      case g: h=(b-r)/d+2; break
      case b: h=(r-g)/d+4; break
    }
    h/=6
  }
  return `hsl(${Math.round(h*360)}, ${Math.round(s*100)}%, ${Math.round(l*100)}%)`
}
const rgb = computed(() => hexToRgb(hex.value))
const hsl = computed(() => hexToHsl(hex.value))
</script>